//问题模块
define('userProblem', ['config', 'cookie', 'jquery', 'handlebars','showBigImg'], function(config, cookie, $, Handlebars,showBigImg){

	//时间戳处理
	function process_timestamp(data){
		var exp = new Date();
		exp.setTime(data);
		//把时间分开装入数组，对只有一位的值进行前补0处理
		var timeArray = [exp.getFullYear(), (exp.getMonth()+1), 
			exp.getDate(), exp.getHours(), exp.getMinutes(), exp.getSeconds()];
		for (var j = 0; j < 6; j++) {
			if (timeArray[j].toString().length == 1){
				timeArray[j] = '0' + timeArray[j];
			}
		}
		var publishTime = timeArray[0] + '.' + timeArray[1] + '.' + timeArray[2]
				+ '  ' + timeArray[3] + ':' + timeArray[4] + ':' + timeArray[5];

		return publishTime;
	}

	function helper(){
		//判断头像是否为空
		Handlebars.registerHelper('if_empty', function(value, options){
			if(value == ''){
				return options.fn(this);
			}
			else{
				return options.inverse(this);
			}
		});
		//判断回答是老师还是画室
		Handlebars.registerHelper('if_studio', function(value, options){
			if(value == 2){
				return options.fn(this);
			}
			else{
				return options.inverse(this);
			}
		});
		//判断content是回答内容还是追问
		Handlebars.registerHelper('if_answer_content', function(value, options){
			if(value == 2 || value == 1){
				return options.fn(this);
			}
			else{
				return options.inverse(this);
			}
		});	
	}

	return {
		getProblemList: function(skip, total, timestamp, userId,avatarUrl){
			var theUrl=config['api']['getAllProblemOfUser'][0].replace(/\<\w+\>/,userId);
			var request = $.ajax({
				url: theUrl,
				type: config['api']['getAllProblemOfUser'][1],
				data: {
					skip: skip,
					total: total,
					timestamp: timestamp,
					userId: userId
				},
				dataType: 'json',
				async: true,
				error: function(err){
					console.log('get problem failed!');
				},
				success: function(data){
					//中心问题模板，用hanlebars生成
					var source = $("#problems-template").html();
					var template = Handlebars.compile(source);

					helper();

					//添加hasImage标记+处理时间戳
					for (var i = 0; i < data['problems'].length; i++) {
						if (data['problems'][i]['image'] != ''){
							data['problems'][i]['hasImage'] = true;
						}

						var publishTime = process_timestamp(data['problems'][i]['timestamp']);
						data['problems'][i]['publishTime'] = publishTime;
					}
					
					data.avatarUrl=avatarUrl;
					console.log("提问",data);
					var myQuestionsComments={};//用以记录评论数据的状态
					$('#myQuestion').html(template(data));
//**************************************************************************
					$(".paintings").on("click","img",function(){
						var src=$(this).attr("src");
						showBigImg(src);
					});//点击看大图


					//展开评论列表
					$("#myQuestion .problem-comment").on("click",".right-comment",function(){
						$(this).parents('.articles').find('.bottom-triangle').css('left', '75%');

						var $this=$(this);
						var $article=$this.closest(".articles");
						var problemid=$article.data("problemid");
						var $commentsBox=$article.find(".show-comments");
						$article.find(".show-answers").hide();//隐藏问题框
						var $commentContent=$commentsBox.find(".main-comments");
						if($commentsBox.is(':hidden') || !$article.find('.main-answers').is(':hidden')){//隐藏状态 + 回答状态
							$commentsBox.show();
							if (!$article.find('.main-answers').is(':hidden')){
								$article.find('.main-answers').hide();
								$article.find('.main-comments').show();
							}

							if(!myQuestionsComments[problemid]){//没有缓存
								$commentContent.html('<div class="comment-content"><h2>加载中..</h2></div>');
								$.ajax({
									url:config.api.getComments[0].replace(/\<\w+\>/,problemid),
									type:config.api.getComments[1],
									success:function(d){
										//处理评论数据
										for (var i = 0; i < d['comments'].length; i++) {
											publishTime = process_timestamp(d['comments'][i]['timestamp']);
											d['comments'][i]['publishTime'] = publishTime;
										}

										renderComment($commentContent,d);
										console.log("展开评论",d);
										myQuestionsComments[problemid]={
											loadedNumber:d.comments.length//已经加载的评论数量
										};

									}
								});

							}else{
								//直接显示
								$commentsBox.show();
							}
							

						}else {//显示状态
							$commentsBox.hide();
						}
					});

					//展开回答列表
					$('#myQuestion .problem-comment').on('click', '.medium-answer', function(){
						var $this = $(this);
						var $articles = $(this).parents('.articles');
						var problemId = $articles.attr('data-problemId');
						$articles.find('.bottom-triangle').css('left', '25%');

						if ($articles.find('.main-answers').is(':hidden')){
							if ($articles.find('.show-comments').is(':hidden')){
								$articles.find('.show-comments').show();
								$articles.find('.main-comments').hide();
								$articles.find('.main-answers').show();
							}
							else{
								$articles.find('.main-comments').hide();
								$articles.find('.main-answers').show();
							}
						}
						else{
							$articles.find('.show-comments').hide();
						}

						var request = $.ajax({
							url: config['api']['getAnswersOfProblem'][0].replace('<problem_id>', problemId),
							type: config['api']['getAnswersOfProblem'][1],
							dataType: 'json',
							async: true,
							error: function(err){
								console.log('get answers failed!');
							},
							success: function(data){
								console.log(data)

								//处理回答数据
								for (var i = 0; i < data['answers'].length; i++) {
									var updateTime_changed = process_timestamp(data['answers'][i]['updateTime']);
									data['answers'][i]['updateTime_changed'] = updateTime_changed;
								}

								var source = $("#answers-template").html();
								var template = Handlebars.compile(source);
								$articles.find('.main-answers').html(template(data))
								if (data['answers'].length == 0){
									$articles.find('.main-answers').html('<h2>暂无回答</h2>');
									$articles.find('.main-answers h2').show();
								}
								
							}
						});
					});

						
					// });
					//渲染评论内容
					function renderComment($ContainerObj,data){
						var source = $("#comments-template").html();
						var template = Handlebars.compile(source);
						$ContainerObj.html(template(data));
					}
				}
			});
		},
		getComments:function(skip, total, timestamp, userId,avatarUrl){
			var theUrl=config['api']['getAllCommentsOfUser'][0].replace(/\<\w+\>/,userId);
			var request = $.ajax({
				url: theUrl,
				type: config['api']['getAllCommentsOfUser'][1],
				data: {
					skip: skip,
					total: total,
					timestamp: timestamp,
					userId: userId
				},
				dataType: 'json',
				async: true,
				error: function(err){
					console.log('get comments failed!');
				},
				success: function(data){
					//中心问题模板，用hanlebars生成
					var source = $("#problems-template").html();
					var template = Handlebars.compile(source);

					helper();

					//添加hasImage标记+处理时间戳
					for (var i = 0; i < data['comments'].length; i++) {
						if (data['comments'][i].problem['image'] != ''){
							data['comments'][i].problem['hasImage'] = true;
						}

						var publishTime = process_timestamp(data['comments'][i]['problem']['timestamp']);
						data['comments'][i]['problem']['publishTime'] = publishTime;
					}
					
					var existedProblemId=[];
					var problems=[];
					data.comments.forEach(function(comment){
						if(existedProblemId.length==0){
							existedProblemId.push(comment.problem._id);
							problems.push(comment.problem);
						}//第一个直接插入 
						var notExist=true;
						for(var i=0,len=existedProblemId.length;i<len;i++){
							if(existedProblemId[i]==comment.problem._id){
								notExist=false;
								break;
							}
						}
						if(notExist){
							existedProblemId.push(comment.problem._id);
							problems.push(comment.problem);
						}
					});//去除重复的问题
					// $(".tab-nav[data-ref=#myComment]").find("span").text(problems.length);
					var problemsData={
						problems:problems,
						avatarUrl:avatarUrl
					};
					console.log("构造的problemData",problemsData);
					var $commentsProblemsList=$('#myComment');
					$commentsProblemsList.html(template(problemsData));

					$(".paintings").on("click","img",function(){
						var src=$(this).attr("src");
						showBigImg(src);
					});//点击看大图
					
					// //展开评论列表
					var commentsRenderFlag={};
					$commentsProblemsList.find(".problem-comment").on("click",".right-comment",function(){
						$(this).parents('.articles').find('.bottom-triangle').css('left', '75%');

						var $this=$(this);
						var $article=$this.closest(".articles");
						var problemid=$article.data("problemid");
						var $commentsBox=$article.find(".show-comments");
						var $commentContent=$commentsBox.find(".main-comments");

						if(!commentsRenderFlag[problemid]){//没有渲染过
							console.log("problemid:",problemid);
							$commentContent.html('<div class="comment-content"><h2>加载中..</h2></div>');

							$.ajax({
								url:config.api.getComments[0].replace(/\<\w+\>/,problemid),
								type:config.api.getComments[1],
								success:function(d){
									//处理评论数据
									for (var i = 0; i < d['comments'].length; i++) {
										publishTime = process_timestamp(d['comments'][i]['timestamp']);
										d['comments'][i]['publishTime'] = publishTime;
									}
									console.log("评论",d);
									renderComment($commentContent,d);
									commentsRenderFlag[problemid]=d.comments.length;//已经加载的评论数量

									
								},
								error:function(){
									alert("获取评论失败");
								}
							});

						}
						if ($commentsBox.is(':hidden')){
							$commentsBox.show();
							$article.find('.main-comments').show();
							$article.find('.main-answers').hide();
						}
						else{
							if (!$article.find('.main-answers').is(':hidden')){
								$article.find('.main-answers').hide();
								$article.find('.main-comments').show();
							}
							else{
								$commentsBox.hide();
							}
						}

					});

					//展开回答列表
					$('#myComment .problem-comment').on('click', '.medium-answer', function(){
						var $this = $(this);
						var $articles = $(this).parents('.articles');
						var problemId = $articles.attr('data-problemId');
						$articles.find('.bottom-triangle').css('left', '25%');

						if ($articles.find('.main-answers').is(':hidden')){
							if ($articles.find('.show-comments').is(':hidden')){
								$articles.find('.show-comments').show();
								$articles.find('.main-comments').hide();
								$articles.find('.main-answers').show();
							}
							else{
								$articles.find('.main-comments').hide();
								$articles.find('.main-answers').show();
							}
						}
						else{
							$articles.find('.show-comments').hide();
						}

						var request = $.ajax({
							url: config['api']['getAnswersOfProblem'][0].replace('<problem_id>', problemId),
							type: config['api']['getAnswersOfProblem'][1],
							dataType: 'json',
							async: true,
							error: function(err){
								console.log('get answers failed!');
							},
							success: function(data){
								console.log(data)

								//处理回答数据
								for (var i = 0; i < data['answers'].length; i++) {
									var updateTime_changed = process_timestamp(data['answers'][i]['updateTime']);
									data['answers'][i]['updateTime_changed'] = updateTime_changed;
								}

								var source = $("#answers-template").html();
								var template = Handlebars.compile(source);
								$articles.find('.main-answers').html(template(data))
								if (data['answers'].length == 0){
									$articles.find('.main-answers').html('<h2>暂无回答</h2>');
									$articles.find('.main-answers h2').show();
								}

								
							}
						});
					});

					//渲染评论内容
					function renderComment($ContainerObj,data){
						var source = $("#comments-template").html();
						var template = Handlebars.compile(source);
						$ContainerObj.html(template(data));
					}

				}
			});
		},

	};
});

/* 返回数据
{
	"problems": [
		{
			"_id": "5548be2a74a2c417976d32d8", 
			"answerNum": 0, "avatarUrl": "", 
			"content": "\u6211\u753b\u5f97\u53fc\u4e0d\u53fc?", 
			"image": "http://img1.imgtn.bdimg.com/it/u=1970000176,1222609041&fm=21&gp=0.jpg", 
			"name": "", 
			"timestamp": 1430830634000, 
			"userId": "5548a54674a2c417976d32d2", 
			"viewNum": 0, 
			"zan": 0
		}, 
		{
			"_id": "5548bdd674a2c417976d32d7", 
			"answerNum": 0, 
			"avatarUrl": "", 
			"content": "\u6211\u753b\u5f97\u53fc\u4e0d\u53fc?", 
			"image": "http://img1.imgtn.bdimg.com/it/u=1970000176,1222609041&fm=21&gp=0.jpg", 
			"name": "", 
			"timestamp": 1430830550000, 
			"userId": "5544f21a74a2c41e8de4c69f", 
			"viewNum": 0, 
			"zan": 0
		}, 
	.......
	],
	"stat": 1
}
*/
